﻿/*
 * Created by SharpDevelop.
 * User: Matjaz
 * Date: 10.11.2007
 * Time: 18:57
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace gopher
{
	/// <summary>
	/// Description of TekstovnoOkno.
	/// </summary>
	public partial class TekstovnoOkno : Form
	{
		public string mojStreznik;
		public string mojSelektor;
		public string mojaVrata;
		public int mojTimeout;
		private bool plus = false;
		public List<string> vrstice;

        printersupport _printdocument = new printersupport();
		
		public TekstovnoOkno(string selektor, string streznik, string vrata, int iTimeout)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");
			InitializeComponent();
			
			mojStreznik = streznik;
			mojSelektor = selektor;
			mojaVrata = vrata;
			mojTimeout = iTimeout;
			vrstice = new List<string>();
		}
		
		static string ReadLine (Stream s)
		{
			List<byte> lineBuffer = new List<byte>();
			while (true)
			{
				int b = s.ReadByte();
				if (b == 10 || b < 0) break;
				if (b != 13) lineBuffer.Add ((byte)b);
			}
			return Encoding.UTF8.GetString (lineBuffer.ToArray());
			//return Encoding.ASCII.GetString (lineBuffer.ToArray());
		}

		static void SendCommand (Stream stream, string line)
		{
			byte[] data = Encoding.UTF8.GetBytes (line + "\r\n");
			//byte[] data = Encoding.ASCII.GetBytes (line + "\r\n");
			stream.Write (data, 0, data.Length);
		}
		
		void TekstovnoOknoLoad(object sender, EventArgs e)
		{
			/*ResourceManager rm = new ResourceManager("gopher.gopherStrings", typeof(TekstovnoOkno).Assembly);
			MessageBox.Show(rm.GetString("hello"));*/
			bool odstraniPrvo = false;
			try
			{
				if(vrstice.Count == 0)
				{
					if(mojSelektor.Contains("\t+"))
					{
						plus = true;
					}
					using (TcpClient client = new TcpClient (mojStreznik, Convert.ToInt32(mojaVrata)))
					using (NetworkStream n = client.GetStream())
					{
						SendCommand (n, mojSelektor);
						
						string plusLine="";
						List<string> imenik = new List<string>();
						StringBuilder SB = new StringBuilder();
						//int x=1000;
						if (n.DataAvailable == false) Thread.Sleep(mojTimeout);
						textBox.Cursor = Cursors.WaitCursor;
						int j = 0;
						int i = 0;
						while(imenik.Count == 0)		//
						{								// večkratna ponovitev če večkrat ne dobimo nič...
							j++;
							while (n.DataAvailable)
							{
								string line = ReadLine (n);
								if(i == 0 && plus)
								{
									plusLine = line;
									if(line.StartsWith("+"))
									{
										line = string.Empty;
										odstraniPrvo = true;
									}
									i++;
								}
								if((plus == false) && (line == ".")) break;
								if((plus) && (plusLine.StartsWith("+-1") && (line == "."))) break;
								if((plus) && (plusLine.StartsWith("--1") && (line == "."))) break;
								SB.Append(line);
								SB.Append(Environment.NewLine);
								
								if (n.DataAvailable == false) Thread.Sleep(mojTimeout);
							}
							if((j == 5) || (imenik.Count != 0))					// poskusimo petkrat
							{								// to je za to, da nimamo večkratnik ponovitev
								break;						//
							}								//
							Thread.Sleep(mojTimeout);		//
						}
//				if(plusLine != "")
//				{
//					MessageBox.Show(plusLine);
//					if(SB.ToString().StartsWith("+"))
//					{
//						SB.Remove(0, SB.ToString().IndexOf("\n"));
//					}
//				}
						if(SB.ToString().StartsWith("--1"))
						{
							string errorMessage = SB.ToString();
							errorMessage = errorMessage.Replace("--1",string.Empty);
							errorMessage = errorMessage.Trim();
							MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
							Close();
						}
						else
						{
							if(odstraniPrvo) SB.Remove(0, Environment.NewLine.Length);
							textBox.Text = SB.ToString();
							textBox.Select(0,0);
							textBox.Cursor = Cursors.Default;
						}
					}
					this.Text = mojSelektor.Substring(mojSelektor.LastIndexOf("\\")+1);
					if(this.Text.Contains("\t"))
					{
						this.Text = this.Text.Substring(0, this.Text.IndexOf("\t"));
					}
				}
				else
				{
					foreach(string vrstica in vrstice)
					{
						textBox.AppendText(vrstica+Environment.NewLine);
					}
				}
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintDialog pd = new PrintDialog();
            _printdocument.Text = textBox.Text;
            _printdocument.Font = textBox.Font;
            pd.Document = _printdocument;
            if (pd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    _printdocument.Print();
                }
                catch (Exception printException)
                {
                    System.Windows.Forms.MessageBox.Show("Printing error\r\n\r\n" + printException.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
        }

        private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog ppd = new PrintPreviewDialog();
            _printdocument.Text = textBox.Text;
            _printdocument.Font = textBox.Font;
            ppd.Document = _printdocument;
            ppd.ShowDialog();

        }

        private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PageSetupDialog psd = new PageSetupDialog();
            psd.Document = _printdocument;
            psd.ShowDialog();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = ("Text file (*.txt)|*.txt|All files (*.*)|*.*");
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                StreamWriter sw = new StreamWriter(saveDialog.FileName);
                sw.Write(textBox.Text);
                sw.Close();
            }
        }
		
		void CopyToolStripButtonClick(object sender, EventArgs e)
		{
			textBox.Copy();
		}
		
		void ExitToolStripMenuItemClick(object sender, EventArgs e)
		{
			Close();
		}
		
		void SelectAllToolStripMenuItemClick(object sender, EventArgs e)
		{
			textBox.SelectAll();
		}
		
		void CopyToolStripMenuItemClick(object sender, EventArgs e)
		{
			textBox.Copy();
		}
		
		void TekstovnoOknoHelpRequested(object sender, HelpEventArgs hlpevent)
		{
			Help.ShowHelp(this, Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\"))+"\\Help\\gopher.chm", "html\\text-window.htm");
		}
	}
}
